package cn.jbolt.ai.common.service.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.common.entity.QiniuConfig;
import cn.jbolt.ai.common.service.CommonService;
import cn.jbolt.util.JSONUtil;
import cn.jbolt.util.QiniuUtil;
import cn.jbolt.util.Result;
import cn.jbolt.util.UploadLocalUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private QiniuUtil qiniuUtil;

    @Autowired
    private UploadLocalUtil uploadLocalUtil;

    private static final Logger logger = LoggerFactory.getLogger(CommonServiceImpl.class);
    /**
     * 获取七牛的相关配置,七牛的上传的token
     *
     * @return 如果配置存在，则返回配置信息；如果不存在，则提示添加配置。
     */
    public Result<QiniuConfig> getQiniuConfig() {
        return qiniuUtil.genUploadToken();
    }


    /**
     * 上传七牛文件并返回七牛地址
     *
     * @param file
     * @return
     */
    public Result uploadFileToQiniu(MultipartFile file) {
        try {
            return qiniuUtil.uploadFile(file.getBytes(), file.getOriginalFilename(),null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("文件上传异常");
    }

    /**
     * 上传本地文件,并返回本地文件地址
     *
     * @param sourceFile
     * @param filePath
     * @return
     */
    @Override
    public Result uploadFileToLocal(MultipartFile sourceFile , String filePath) {
        if (sourceFile .isEmpty()) {
            return Result.error("请选择要上传的文件");
        }
        if(StrUtil.isEmpty(filePath)){
            return Result.error("请输入文件路径");
        }
        try {
            Result<String> result = uploadLocalUtil.uploadFileToLocal(sourceFile, filePath);
            if (result.isSuccess()){
                ObjectNode objectNode = JSONUtil.createObjectNode();
                objectNode.put("url", result.getData());
                return Result.success(objectNode);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("文件上传失败：" + e.getMessage());
            return Result.error("文件上传失败");
        }
    }
}
